package com.briup.myblog.service.impl;

import com.briup.myblog.bean.basic.Comment;
import com.briup.myblog.bean.ext.CommentExt;
import com.briup.myblog.dao.ext.CommentExtMapper;
import com.briup.myblog.exception.CustomerException;
import com.briup.myblog.service.ICommentService;
import com.briup.myblog.utils.ResultUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


@Slf4j
@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentExtMapper mapperExt;

    @Override
    public void checkComment(int id, int status) {
        mapperExt.checkComment(id, status);
    }

    @Override
    public PageInfo<CommentExt> pageQuery(int pageNum, int pageSize, String keywords) {
        List<CommentExt> list = mapperExt.selectCommentByPageHelper(keywords);
        PageInfo<CommentExt> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void deleteById(int id) {
        findChildComment(id);
    }

    //查找子评论
    public void findChildComment(Integer id) {
        //查找子评论
        List<CommentExt> list = mapperExt.findParentId(id);
        //存在子评论，先删子评论，再删父评论
        if (list.size() != 0) {
            for (int i=0; i<list.size();i++){
                //递归查找子评论
                findChildComment(list.get(i).getCommentId());
            }
        }
        //删除父评论
        mapperExt.deleteCommentById(id);
    }

    @Override
    public void batchDelete(Integer[] ids) {
        Arrays.sort(ids, Collections.reverseOrder());//排序
        for (int i = 0; i < ids.length; i++) {
            List<CommentExt> list = mapperExt.findParentId(ids[i]);//根据id查找评论信息
            if (list.size() != 0) {
                deleteById(ids[i]);//调用方法
            }
            mapperExt.deleteCommentById(ids[i]);//删除评论
        }

            /*for (int i = 0; i < ids.length; i++) {
                mapperExt.deleteCommentById(ids[i]);
            }*/
    }
}
